<?php

namespace App\Admin\Controllers;

include base_path() . '/vendor/autoload.php';

use DB;
use Validator;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use EasyWeChat\Foundation\Application;
use App\Agent;
use App\PublicGemsLog;
use App\User;
use App\Club;
use App\ClubUser;
use App\ClubRoomRecord;

class AgentController extends Controller
{
    protected $options = [
        'debug' => true,
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',
        'token' => '',
    ];

	/**
	 * [index description]
	 * @return [type] [description]
	 */
	public function index(Request $request)
	{
		$keywords = $request->input('keywords');
		$agents = Agent::where(['status' => 0, 'pid' => 0]);
		if ($keywords) {
			$agents = $agents->where('realname', 'like', '%'.$keywords.'%');
		}
		$agents = $agents->paginate(15);
		$agents = $agents->appends([
			'keywords' => $keywords
			]);

		return view('admin.agent.index', compact('agents', 'keywords'));
	}

	/**
	 * [list description]
	 * @return [type] [description]
	 */
	public function list(Request $request)
	{
		$keywords = $request->input('keywords');
		$agents = Agent::where(['status' => 1, 'pid' => 0]);
		if ($keywords) {
			$agents = $agents->where('realname', 'like', '%'.$keywords.'%')->orWhere('mobile', 'like', '%'.$keywords.'%');
		}
		$agents = $agents->orderBy('pass_time', 'DESC')->paginate(15);
		$agents = $agents->appends([
			'keywords' => $keywords
			]);

		return view('admin.agent.list', compact('agents', 'keywords'));
	}

	/**
	 * [audit description]
	 * @param  Agent  $agent [description]
	 * @return [type]        [description]
	 */
	public function audit(Agent $agent)
	{
		return view('admin.agent.audit', compact('agent'));
	}

	/**
	 * [auditStore description]
	 * @return [type] [description]
	 */
	public function auditStore(Agent $agent, Request $request)
	{	
    	$validator = Validator::make($request->all(), [
			'status' => 'required',
			'divide' => 'numeric|max:100|min:1'
        ], [
        	'status.required' => '选择状态',
        	'divide.numeric' => '分成比例为整数',
        	'divide.max' => '分成比例不超过100',
        	'divide.min' => '分成比例不少于1',
        	]);
    	if ($request->input('status') == 1) {
    		$divide = $request->input('status');
    		if (!$divide) {
	    		$validator->after(function($validator){
		            $validator->errors()->add('divide', '设置分成比例');
		        });
    		}
    	}
        if ($validator->passes()) {
        	$agent->status = $request->input('status');
        	$agent->reject_reason = $request->input('reason');
        	if ($request->input('divide')) {
        		$agent->divide = $request->input('divide');
        	}
        	$agent->pass_time = time();
        	$agent->save();
        	if ($request->input('status') == 1) {
        		$user = $agent->user();
        		if ($user) {
        			$user->agent = 1;//开启亲友圈
        			$user->save();
        		}
        		/*自动创建俱乐部*/
        		$club = new Club;
        		$club->club_id = str_pad(mt_rand(1, 999999), 5, '0', STR_PAD_LEFT);
        		$club->club_name = base64_encode(base64_decode($user->name)."的亲友圈");
        		$club->creator = $user->userid;
        		$club->create_time = time();
        		$club->hotpush = 1;
        		$club->description = base64_decode($user->name)."的亲友圈";
        		$club->maxrooms = 5;
        		$club->club_fangfei = 0;
        		$club->limitpeople = 30;
        		$club->type = 1;
        		$club->save();
        		$club_user = new ClubUser;
        		$club_user->club_id = $club->club_id;
        		$club_user->userid = $user->userid;
        		$club_user->join_time = time();
        		$club_user->state = 999;
        		$club_user->save();

	            $app = new Application($this->options);
	            $notice = $app->notice;
	            $userService = $app->user;
	            $member = $userService->get($agent->open_id);
	            $subscribe = $member->subscribe;
	            if ($subscribe) {
		            $openId = $agent->open_id;
		            $templateId = 'q3kyGYoZalQ0fpCF57ipnMO__mwnoXLrZOSZOSQBjDY';
		            $url = url("/mobile/index");
		            $data = array(
		                "first" => "恭喜您通过了推广员审核，并为您开启了亲友圈!",
		                "keyword1" => "审核通过",
		                "keyword2" => "乐游手游一级推广员申请",
		                "keyword3" => date('Y-m-d H:i', $agent->shenqing_time),
		                "keyword4" => date('Y-m-d H:i', $agent->pass_time),
		                "remark" => "开启乐游之旅!",
		            );
		            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
	        	}
        	}

	    	return ['flag' => true, 'msg' => '设置成功'];
        } else {
        	return $validator->errors();
        }	
	}

	/**
	 * [secondList description]
	 * @return [type] [description]
	 */
	public function secondList(Agent $agent)
	{
		$agents = Agent::where(['status' => 1, 'pid' => $agent->id]);
		$agents = $agents->paginate(15);

		return view('admin.agent.secondlist', compact('agents'));
	}

	/**
	 * [assignCard description]
	 * @return [type] [description]
	 */
	public function assignCard(Agent $agent)
	{
		return view('admin.agent.assign', compact('agent'));
	}

	/**
	 * [storeCard description]
	 * @return [type] [description]
	 */
	public function storeCard(Agent $agent, Request $request)
	{
		$validator = Validator::make($request->all(), [
			'gems' => 'required|numeric|min:1'
        ], [
        	'gems.required' => '请输入房卡数量',
        	'gems.numeric' => '房卡数量只能为整数',
        	'gems.min' => '房卡数量不少于1'
        	]);
        if ($validator->passes()) {
        	$user = $agent->user();
        	$user->gems += $request->input('gems');
        	$log = new PublicGemsLog;
        	$log->type = 1;
        	$log->accept_id = $agent->id;
        	$log->gems = $request->input('gems');
			DB::beginTransaction();
	    	try{
	    		$user->save();
	    		$log->save();
	        	DB::commit();

	        	return ['flag' => true, 'msg' => '分配成功'];
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		return ['flag' => true, 'msg' => '事务执行失败，数据回滚'];
	    	}
        } else {
        	return $validator->errors();
        }	
	}

	/**
	 * [assignLog 接收记录]
	 * @return [type] [description]
	 */
	public function assignLog(Agent $agent, Request $request)
	{
		$type = $request->input('type');
		$logs = PublicGemsLog::where(['type' => $type, 'accept_id' => $agent->id])->orderBy('created_at', 'DESC')->paginate(15);

		return view('admin.agent.assignlog', compact('logs'));
	}

	/**
	 * [sendLog 分配记录]
	 * @return [type] [description]
	 */
	public function sendLog(Agent $agent, Request $request)
	{
		$type = $request->input('type');
		if ($type == 2) {
			$logs = PublicGemsLog::where(['send_id' => $agent->id])->whereIn('type', [2, 3])->orderBy('created_at', 'DESC')->paginate(15);

			return view('admin.agent.assignlog', compact('logs'));
		} else {
			$logs = PublicGemsLog::where(['type' => $type, 'send_id' => $agent->id])->orderBy('created_at', 'DESC')->paginate(15);

			return view('admin.agent.sendLog', compact('logs'));
		}
	}

	/**
	 * [remove description]
	 * @return [type] [description]
	 */
	public function remove(Agent $agent)
	{
		$agent->delete();
		return ['flag' => true];
	}

	/**
	 * [openCircle 开启会员亲友圈]
	 * @return [type] [description]
	 */
	public function openCircle(Agent $agent)
	{
		return view('admin.agent.openCircle', compact('agent'));
	}

	/**
	 * [storeCircle 会员亲友圈设置]
	 * @param  Agent   $agent   [description]
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function storeCircle(Agent $agent, Request $request)
	{
		$validator = Validator::make($request->all(), [
			'open_circle' => 'required',
			'circle_divide' => 'required|max:100|min:0'
        ], [
        	'open_circle.required' => '亲友圈状态必选',
        	'circle_divide.required' => '分成比例必填',
        	'circle_divide.max' => '分成比例不超过100',
        	'circle_divide.min' => '分成比例不少于0'
        	]);
        if ($validator->passes()) {
        	$agent->open_circle = $request->input('open_circle');
        	$agent->circle_divide = $request->input('circle_divide');
        	$agent->save();
        	return ['flag' => true, 'msg' => '设置成功'];
        } else {
        	return $validator->errors();
        }
	}

	/**
	 * [setDivide 设置分成比例]
	 */
	public function setDivide(Agent $agent)
	{
		return view('admin.agent.setDivide', compact('agent'));
	}

	/**
	 * [storeDivide 保存分成比例]
	 * @return [type] [description]
	 */
	public function storeDivide(Agent $agent, Request $request)
	{
		$validator = Validator::make($request->all(), [
			'divide' => 'required|max:100|min:0'
        ], [
        	'divide.required' => '分成比例必填',
        	'divide.max' => '分成比例不超过100',
        	'divide.min' => '分成比例不少于0'
        	]);
        if ($validator->passes()) {
        	$agent->divide = $request->input('divide');
        	$agent->save();
        	return ['flag' => true, 'msg' => '设置成功'];
        } else {
        	return $validator->errors();
        }
	}

	/**
	 * [dvlpUsers 发展的玩家]
	 * @return [type] [description]
	 */
	public function dvlpUsers(Agent $agent)
	{
		$users = User::where(['daili_id' => $agent->id])->orderBy('created_at', 'DESC')->limit(10)->get();
		return view('admin.agent.dvlpusers', compact('users', 'agent'));
	}

	/**
	 * [dvlpLoad 发展的玩家]
	 * @return [type] [description]
	 */
	public function dvlpLoad(Agent $agent, Request $request)
	{
		if (!$request->input('page')) {
			return ['flag' => false, 'msg' => 'page不能为空'];
		}
		if (!$request->input('pagesize')) {
			return ['flag' => false, 'msg' => 'pagesize不能为空'];
		}
		$keywords = $request->input('keywords');
		$limit = ($request->input('page') - 1) * $request->input('pagesize');
		$data = User::where(['daili_id' => $agent->id])->orderBy('created_at', 'DESC');
		if ($keywords) {
			$data->where(function($query) use ($keywords) {
				$query->where('name', 'like', '%'.base64_encode($keywords).'%')->orWhere('userid', 'like', '%'.$keywords.'%')->orWhere('created_at', 'like binary', '%'.$keywords.'%');
			});
		}
		$data = $data->offset($limit)->limit($request->input('pagesize'))->get();
		$re_data = [];
		if ($data) {
			foreach ($data as $da) {
				array_push($re_data, ['userid' => $da->userid, 'name' => base64_decode($da->name), 'headimg' => $da->headimg, 'gems' => $da->gems, 'money' => $da->money, 'created_at' => $da->created_at ? Carbon::parse($da->created_at)->toDateTimeString(): '']);
			}
		}
		if ($re_data) {
			return ['flag' => true, 'data' => $re_data];
		} else {
			return ['flag' => false, 'msg' => '暂无更多'];
		}
	}

	/**
	 * [gemsLog 房卡分接记录]
	 * @return [type] [description]
	 */
	public function gemsLog(Agent $agent)
	{
		$accepts = PublicGemsLog::where(['type' => 1, 'accept_id' => $agent->id])->orderBy('created_at', 'DESC')->get();
		$sends = PublicGemsLog::where(['send_id' => $agent->id])->whereIn('type', [2, 3])->orderBy('created_at', 'DESC')->get();
		return view('admin.agent.gemslog', compact('accepts', 'sends'));
	}

	/**
	 * 亲友圈统计
	 */
	public function circleLog(Agent $agent, Request $request)
	{
		$total = 0;
		$data = json_encode([]);
		$period = "";
		$games = [];
		$club_id = $request->input('club_id');
		if ($request->input('time')) {
			$period = $request->input('time') ? $request->input('time') : date('Y-m-d', time()) . '~' . date('Y-m-d', strtotime('+1 day'));
			$time_arr = explode('~', $period);
			$begin = strtotime($time_arr[0]).'000';
			$end = strtotime($time_arr[1]).'000';
			if ($request->input('type') == 1) {//全部
				$total = ClubRoomRecord::whereBetween('end_time', [$begin, $end])->where(['club_id' => $club_id])->where(function($query){
					$query->where('info', 'like', '%"type":"kdd"%')->orWhere('info', 'like', '%"type":"tdh"%')->orWhere('info', 'like', '%"type":"htwp"%')->orWhere('info', 'like', '%"type":"xzkdd"%')->orWhere('info', 'like', '%"type":"jz"%');
				})->get()->count();
				//扣点点
				$kdd = ClubRoomRecord::where('info', 'like', '%"type":"kdd"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				//推到胡
				$tdh = ClubRoomRecord::where('info', 'like', '%"type":"tdh"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				//洪洞王牌
				$htwp = ClubRoomRecord::where('info', 'like', '%"type":"htwp"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				//忻州扣点点
				$xzkdd = ClubRoomRecord::where('info', 'like', '%"type":"xzkdd"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				//晋中麻将
				$jz = ClubRoomRecord::where('info', 'like', '%"type":"jz"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				if ($kdd > 0 || $tdh > 0 || $htwp > 0 || $xzkdd > 0 || $jz > 0) {
					$data = [
						['扣点点', $kdd],	
						['推到胡', $tdh],
						['洪洞王牌', $htwp],
						['忻州扣点点', $xzkdd],
						['晋中麻将', $jz]
					];
					$data = json_encode($data);
				}
			} else if ($request->input('type') == 2) {//扣点点
				$total = ClubRoomRecord::where('info', 'like', '%"type":"kdd"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				//扣点点
				$kdd = ClubRoomRecord::where('info', 'like', '%"type":"kdd"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				
				if ($kdd > 0) {
					$data = [
						['扣点点', $kdd]
					];
					$data = json_encode($data);
				}

			} else if ($request->input('type') == 3) {//推倒胡
				$total = ClubRoomRecord::where('info', 'like', '%"type":"tdh"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				$tdh = ClubRoomRecord::where('info', 'like', '%"type":"tdh"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				
				if ($tdh > 0) {
					$data = [
						['推倒胡', $tdh]
					];
					$data = json_encode($data);
				}

			} else if ($request->input('type') == 4) {//洪洞王牌
				$total = ClubRoomRecord::where('info', 'like', '%"type":"htwp"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				$htwp = ClubRoomRecord::where('info', 'like', '%"type":"htwp"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				
				if ($htwp > 0) {
					$data = [
						['洪洞王牌', $htwp]
					];
					$data = json_encode($data);
				}

			} else if ($request->input('type') == 5) {//忻州扣点
				$total = ClubRoomRecord::where('info', 'like', '%"type":"xzkdd"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				$xzkdd = ClubRoomRecord::where('info', 'like', '%"type":"xzkdd"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				
				if ($xzkdd > 0) {
					$data = [
						['忻州扣点', $xzkdd]
					];
					$data = json_encode($data);
				}

			} else if ($request->input('type') == 6) {//晋中麻将
				$total = ClubRoomRecord::where('info', 'like', '%"type":"jz"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				$jz = ClubRoomRecord::where('info', 'like', '%"type":"jz"%')->where(['club_id' => $club_id])->whereBetween('end_time', [$begin, $end])->get()->count();
				
				if ($jz > 0) {
					$data = [
						['晋中麻将', $jz]
					];
					$data = json_encode($data);
				}

			}
		}
		return view('admin.agent.circleLog', compact('total', 'period', 'agent', 'data'));
	}

	/**
	 * 亲友圈统计筛选
	 */
	public function circleLogFilter(Agent $agent)
	{
		$user = $agent->user();
		$clubs = ClubUser::select(DB::raw('t_club.club_id, t_club.club_name, t_club.type'))->where(['t_club_users.userid' => $user->userid, 't_club_users.state' => 999])->join('t_club', function($join){
			$join->on('t_club_users.club_id', '=', 't_club.club_id');
		})->get();
		return view('admin.agent.circleLogFilter', compact('clubs', 'agent'));
	}

}	